import { createFetch } from "@vueuse/core";
import type { AfterFetchContext } from "@vueuse/core";
import createEmitter from "@/components/emitter";
// 创建 http 事件总线
export const httpEvent = createEmitter<{
  request: RequestInit;
  response: AfterFetchContext;
  error: { error: any; data: any; response: Response | null };
}>();

// 实例化基本的fetch
export const useApiFetch = createFetch({
  baseUrl: import.meta.env.VITE_BASE_URL,
  options: {
    async beforeFetch({ options }) {
      httpEvent.emit("request", options);
      return {
        options,
      };
    },
    async afterFetch(ctx) {
      httpEvent.emit("response", ctx);
      return ctx;
    },
    async onFetchError(ctx) {
      httpEvent.emit("error", ctx);
      return ctx;
    },
  },
  fetchOptions: {},
});

// 定义 API 数据接口格式
export interface ApiResponse<T = any> {
  success: boolean;
  query: {
    count: number;
    results: Array<T>;
    limit: number;
    offset: number;
    page: number;
  };
  object: T;
  message: string;
  errors: {
    [propName: string]: Array<string>;
  };
}
